package com.dinner.struts.action;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dinner.model.Administrator;
import com.dinner.model.Consumer;
import com.dinner.model.DinnerUser;
import com.dinner.model.Seller;
import com.dinner.service.UserLoginService;
import com.dinner.struts.form.UserLoginForm;

public class UserLoginAction extends Action {

	private UserLoginService service = null;

	/**
	 * @param service the service to set
	 */
	public void setService(UserLoginService service) {
		this.service = service;
	}

	/**
	 * @return the service
	 */
	public UserLoginService getService() {
		return service;
	}
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
			
		HttpSession session = request.getSession();
		UserLoginForm loginForm = (UserLoginForm) form;
		
		DinnerUser user = service.getUser(loginForm.getUserID(),
				loginForm.getPassword(), loginForm.getType());
		if (user == null) {
			request.setAttribute("message", "Login Failure.");
			return mapping.findForward("LoginError");
		}
		
		session.setAttribute("user", user);
		Class<? extends DinnerUser> clazz = user.getClass();
		return map.get(clazz).getActionForward(mapping);
	}
	
	private static abstract class ActionForwardGetter {
		public abstract ActionForward getActionForward(ActionMapping mapping);
	}
	
	private static class StringActionForwardGetter extends ActionForwardGetter {
		private String forward = null;
		public StringActionForwardGetter(String forward) {
			this.forward = forward;
		}
		@Override 
		public ActionForward getActionForward(ActionMapping mapping) {
			return mapping.findForward(forward);
		}
	}
	
	private final static HashMap<Class<? extends DinnerUser>, ActionForwardGetter> map;
	static {
		map = new HashMap<Class<? extends DinnerUser>, ActionForwardGetter>();
		map.put(Seller.class, new StringActionForwardGetter("SellerMainPage"));
		map.put(Administrator.class, new StringActionForwardGetter("AdminMainPage"));
		map.put(Consumer.class, new ActionForwardGetter() {
			@Override
			public ActionForward getActionForward(ActionMapping mapping) {
				String url = mapping.getInput();
				ActionForward gotourl = new ActionForward(url);
				gotourl.setPath(url);
				gotourl.setRedirect(true);
				return gotourl;
			}
		});
	}
}
